;(function (window,$) {
    // 创建表单验证对象
    function Validate(validateRules,callback) {
        return new Validate.prototype.init(this,validateRules,callback);
    }
    Validate.prototype = {
        constructor:Validate,
        init:function (form,validateRules,callback) {
            this.formControls = [];
            this._init(form,validateRules);
            this.check(callback);
        },
        _init:function (form,validateRules) {
            var _form = form.get(0);
            for (let validateRulesKey in validateRules) {
                if (validateRules.hasOwnProperty(validateRulesKey)) {
                    this.formControls.push({
                         el:_form[validateRulesKey],
                         name:validateRulesKey,
                         rule:validateRules[validateRulesKey]
                    })
                }
            }
        },
        check:function (callback) {
            var resValue = {};
            var res = true;
            var count = 0;
            this.formControls.forEach(function (rules,index) {
                var pattern = rules.rule.pattern;
                if (pattern instanceof  RegExp){
                     res =  pattern.test(rules.el.value);
                     if (res){
                         count++;
                         resValue[rules.name] = rules.el.value;
                         this.showSetClass(rules);
                     }else{
                         this.hideSetClass(rules);
                         count--;
                     }
                }
                if (pattern instanceof Function){
                     res =  pattern(rules.el.value);
                    if (res){
                        count++;
                        resValue[rules.name] = rules.el.value;
                        this.showSetClass(rules);
                    }else{
                        this.hideSetClass(rules);
                        count--;
                    }
                }
            }.bind(this));
            if (count === this.formControls.length) callback(resValue);
            else callback(false)
        },
        showSetClass:function (rules) {
            $(rules.el).nextSlibing().find(rules.rule.errSelector)
                .removeClass(rules.rule.showClassName)
                .addClass(rules.rule.hideClassName)
                .text(rules.rule.errText)
        },
        hideSetClass:function (rules) {
            $(rules.el).nextSlibing().find(rules.rule.errSelector)
                .removeClass(rules.rule.hideClassName)
                .addClass(rules.rule.showClassName)
                .text(rules.rule.errText);
        }
    };
    Validate.prototype.init.prototype = Validate.prototype;
    // 给Utils进行扩展
    $.fn.extends({validate:Validate})
})(window,Util);